<template>
  <view class="order-submission">
    <view
      class="allAddress"
      :style="systemStore ? '' : 'padding-top: 0.2*100rpx'"
    >
      <view
        class="address acea-row row-between-wrapper"
        v-if="shipping_type === 0"
        @click="addressTap"
      >
        <view class="address-1"
          ><text
            class="theme address-icon iconfont icon-a-locationhl"
            style="color: #1F2329"
          ></text>
        </view>
        <view class="addressCon" v-if="addressInfo.id">
          <view class="name">
            {{ addressInfo.realName }}
            <text class="phone">{{ addressInfo.phone }}</text>
          </view>
          <view>
            <text class="default font-color-red" v-if="addressInfo.isDefault=='1'"
              >[默认]</text
            >
            {{ addressInfo.province }}{{ addressInfo.city
            }}{{ addressInfo.district }}{{ addressInfo.detail }}
          </view>
        </view>
        <view class="addressCon" v-else>
          <view class="setaddress">设置收货地址</view>
        </view>
        <view class="iconfont icon-more1"></view>
      </view>
      <view
        class="address acea-row row-between-wrapper"
        v-if="shipping_type === 1"
        @click="showStoreList"
      >
        <view class="addressCon" v-if="storeItems">
          <view class="name">
            {{ storeItems.name }}
            <span class="phone">{{ storeItems.phone }}</span>
          </view>
          <view>{{ storeItems.address }}</view>
        </view>
        <view class="addressCon" v-else>
          <view class="name">
            {{ systemStore.name }}
            <span class="phone">{{ systemStore.phone }}</span>
          </view>
          <view>{{ systemStore.address }}</view>
        </view>
        <view class="iconfont icon-more1"></view>
      </view>
    </view>
    <OrderGoods
      :evaluate="0"
      :isIntegral="isIntegral"
      :cartInfo="orderGroupInfo.cartInfo"
    ></OrderGoods>
    <view class="wrapper">
      <view
        class="item acea-row row-between-wrapper"
        v-if="orderPrice.totalPrice !== undefined"
      >
        <view class="title">{{ isIntegral ? '支付积分' : '支付金额' }}</view>
        <view class="money" v-if="!isIntegral"
          >￥{{ orderPrice.totalPrice }}</view
        >
        <view class="money" v-if="isIntegral"
          >{{ orderPrice.payIntegral }}积分</view
        >
      </view>
      <view
        v-if="shipping_type === 0"
        class="item acea-row row-between-wrapper"
      >
        <view class="title">运费</view>
        <view class="discount fontColor">
          {{ orderPrice.payPostage > 0 ? orderPrice.payPostage : '免运费' }}
        </view>
      </view>
      <!-- 12小时内送达 --><!-- 20250804-zh -->
      <!-- <view class="item acea-row row-between-wrapper" v-if="todayDelivery">
        <view class="title">12小时内送达</view>
        <view class="fontColor">
          <u-switch
            v-model="sameDayDelivery"
            activeColor="#FF5900"
            asyncChange
            @change="asyncChangeTodayDelivery"
          ></u-switch>
        </view>
      </view>
      <view
        v-if="todayDelivery && sameDayDelivery"
        class="item acea-row row-between-wrapper"
      >
        <view class="title">
          当日{{ todayDelivery.cutOffTimeForSameDayDelivery }}前可选
        </view>
        <view class="fontColor">
          配送费:￥{{ todayDelivery.sameDayDeliveryPrice || 0 }}
        </view>
      </view>--><!-- 20250804-zh -->
      <view
        class="item acea-row row-between-wrapper"
        @click="couponTap"
        v-if="deduction === false && !isIntegral"
      >
        <view class="title">优惠方式</view>
        <view class="discount">
          {{ usableCoupon.couponTitle || '请选择' }}
          <text class="iconfont icon-more1"></text>
        </view>
      </view> 
      
    </view>

    <view class="footer acea-row row-between-wrapper box">
      <view>
        合计:
        <text class="font-color-red" v-if="!isIntegral"
          >￥{{ orderPrice.payPrice }}</text
        >
        <!-- <text class="font-color-red" v-if="isIntegral"
          >{{ orderPrice.payIntegral }}积分</text
        > -->
      </view>
      <view class="settlement" @click="createOrder">立即结算</view>
    </view>

    <CouponListWindow
      v-on:couponchange="changecoupon($event)"
      v-model="showCoupon"
      :price="orderPrice.totalPrice"
      :checked="usableCoupon.id"
      :cartid="cartid"
      @checked="changeCoupon"
    ></CouponListWindow>

    <AddressWindow
      @checked="changeAddress"
      @redirect="addressRedirect"
      v-model="showAddress"
      :checked="addressInfo.id"
      ref="mychild"
    ></AddressWindow>
  </view>
</template>

<style scoped lang="less">
.order-submission .wrapper .shipping select {
  color: #999;
  padding-right: 0.15 * 100rpx;
}
.order-submission .wrapper .shipping .iconfont {
  font-size: 0.3 * 100rpx;
  color: #515151;
}
.order-submission .allAddress {
  // width: 100%;

  // background-image: linear-gradient(to bottom, #ff6010 0%, #ff6010 100%);

  // background-image: -webkit-linear-gradient(to bottom, #ff6010 0%, #ff6010 100%);

  // background-image: -moz-linear-gradient(to bottom, #ff6010 0%, #ff6010 100%);

  // padding-top: 1 * 100rpx;
}
.order-submission .allAddress .nav {
  margin: 0 auto;
  padding: 0 30rpx;
  width: 100%;
  box-sizing: border-box;
}
.order-submission .allAddress .nav .item {
  flex: 1;
  position: relative;
}
.order-submission .allAddress .nav .item.on {
  position: relative;
}
.order-submission .allAddress .nav .item.on:before {
  position: absolute;
  bottom: 0;
  content: '快递配送';
  font-size: 0.28 * 100rpx;
  display: block;
  height: 0;
  left: 0;
  right: 0;
  border-width: 0.4 * 100rpx;
  border-style: solid;
  border-color: #fff;
  z-index: 9;
  text-align: center;
  line-height: 0.14 * 100rpx;
}
.order-submission .allAddress .nav .item:nth-of-type(2).on:before {
  content: '到店自提';
  border-width: 0.4 * 100rpx;
}
.order-submission .allAddress .nav .item.on2 {
  position: relative;
}
.order-submission .allAddress .nav .item.on2:before {
  position: absolute;
  bottom: 0;
  content: '到店自提';
  font-size: 0.28 * 100rpx;
  display: block;
  height: 0;
  left: 0;
  right: 0;
  border-width: 0.4 * 100rpx;
  border-style: solid;
  border-color: #d5e6e6;
  text-align: center;
  line-height: 0.14 * 100rpx;
}

.order-submission .allAddress .nav .item:nth-of-type(1).on2:before {
  content: '快递配送';
  border-width: 0.4 * 100rpx;
}
.order-submission .allAddress .address {
  width: 6.91 * 100rpx;
  height: 1.5 * 100rpx;
  margin: 0 auto;
  box-sizing: border-box;
}
.order-submission .allAddress .line {
  width: 7.1 * 100rpx;
  margin: 0 auto;
}
.order-submission .wrapper .item .discount input::placeholder {
  color: #ccc;
}

.wrapper {
  margin: 16rpx 24rpx;
  border-radius: 20rpx;

  .money {
    font-size: 36rpx;
    color: #1a1a1a;
    font-weight: 500;
  }

  .fontColor {
    font-size: 30rpx !important;
    color: #1a1a1a !important;
  }

  .title {
    font-size: 30rpx;
    color: #1a1a1a;
  }
}

.box {
  justify-content: flex-end;
  font-size: 24rpx;
  color: #1a1a1a;

  .settlement {
    background-color: #FF5900;
  }

  .font-color-red {
    font-size: 36rpx;
    font-weight: 500;
    margin-right: 24rpx;
  }
}
</style>

<script>
import OrderGoods from '@/packageShop/components/OrderGoods'
import CouponListWindow from '@/packageShop/components/CouponListWindow'
import AddressWindow from '@/packageShop/components/AddressWindow'
import {
  postOrderConfirm,
  postOrderComputed,
  createOrder,
  getOrderExpressConfig,
} from '@/api/order'
import { mapGetters, mapState } from 'vuex'
import { handleOrderPayResults, subscribeMessage } from '@/libs/order'
import { isWeixin, handleErrorMessage } from '@/utils'
import dayjs from 'dayjs'
const NAME = 'OrderSubmission'

let _isWeixin = isWeixin()

/* #ifdef MP-WEIXIN */

_isWeixin = true

/* #endif */

export default {
  name: NAME,

  components: {
    OrderGoods,

    CouponListWindow,

    AddressWindow,
  },

  props: {},

  data: function () {
    return {
      sameDayDelivery: false, // 是否启用今日送达
      todayDelivery: null, // 12小时内送达配送
      offlinePayStatus: 2,

      from: this.$deviceType,

      deduction: true,

      enableIntegral: true,

      enableIntegralNum: 0,

      isWeixin: _isWeixin,

      pinkId: 0,

      active: _isWeixin ? 'weixin' : 'yue',

      showCoupon: false,

      showAddress: false,

      addressInfo: {},

      couponId: 0,

      orderGroupInfo: {
        priceGroup: {},
      },

      usableCoupon: {},

      addressLoaded: false,

      useIntegral: false,

      orderPrice: {
        payPrice: '计算中',
      },

      mark: '',

      systemStore: {},

      shipping_type: 0,

      contacts: '',

      contactsTel: '',

      storeSelfMention: 0,

      cartid: '',

      isIntegral: false,
    }
  },

  computed: {
    ...mapGetters(['userInfo', 'storeItems']),
    ...mapState('user', ['UserInfo', 'token', 'isIOS']),
    // 是否可以开启 12小时内送达
    jsTodayDelivery() {
      if (
        this.todayDelivery &&
        this.todayDelivery.sameDayDeliveryEnable &&
        this.isCurrentTimeAfter(
          this.todayDelivery.cutOffTimeForSameDayDelivery
        ) &&
        this.todayDelivery.supportCity == this.addressInfo.city
      ) {
        return false
      } else return true
    },
  },

  watch: {
    useIntegral() {
      this.computedPrice()
    },

    shipping_type() {
      this.computedPrice()
    },
  },

  onLoad: function () {
    let that = this
    that.getOrderConfig()
    this.$store.dispatch('getUser', true)

    that.getCartInfo()
    this.$refs.mychild.getAddressList()
    // console.log(that.$yroute)

    if (that.$yroute.query.pinkid !== undefined) {
      that.pinkId = that.$yroute.query.pinkid
    }

    this.isIntegral = that.$yroute.query.isIntegral == 'true'

    this.useIntegral = this.isIntegral

    if (this.isIntegral) {
      this.active = 'integral'
    }

    // if (that.$yroute.query.id !== undefined) {
    //   that.cartid = that.$yroute.query.id

    //   console.log(that.cartid)
    // }
  },

  methods: {
    // 订单信息
    getOrderConfig() {
      getOrderExpressConfig().then(res => {
        console.log(res, '---------------')
        //今日送达配置
        if (res.status == 200) {
          this.todayDelivery = res.data
          this.isCurrentTimeAfter(
            this.todayDelivery.cutOffTimeForSameDayDelivery
          )
        }
      })
    },
    // 12小时内送达
    asyncChangeTodayDelivery(e) {
      if (
        this.todayDelivery &&
        this.todayDelivery.sameDayDeliveryEnable &&
        this.isCurrentTimeAfter(
          this.todayDelivery.cutOffTimeForSameDayDelivery
        ) &&
        this.todayDelivery.supportCity == this.addressInfo.city
      ) {
        this.sameDayDelivery = e
        this.computedPrice()
      } else {
        if (this.todayDelivery.supportCity != this.addressInfo.city) {
          return uni.$u.toast('当前地址不支持12小时内送达')
        }
        if (
          !this.isCurrentTimeAfter(
            this.todayDelivery.cutOffTimeForSameDayDelivery
          )
        ) {
          return uni.$u.toast(
            `当日${this.todayDelivery.cutOffTimeForSameDayDelivery}前可用`
          )
        }
      }
    },
    // 判断时间点
    isCurrentTimeAfter(time) {
      // 获取当前时间
      let nowUnix = dayjs(new Date()).unix()
      let date = dayjs(new Date()).format('YYYY-MM-DD')
      let deadline = date + ' ' + time
      let deadUnix = dayjs(deadline).unix()
      // 判断当前时间是否大于目标时间
      return nowUnix < deadUnix
    },
    showStoreList() {
      this.$store.commit('get_to', 'orders')

      this.$yrouter.push({
        path: '/packageShop/pages/shop/StoreList/index',
      })
    },

    addressType: function (index) {
      if (index && !this.systemStore.id) {
        uni.showToast({
          title: '暂无门店信息，您无法选择到店自提！',

          icon: 'none',

          duration: 2000,
        })

        return
      }

      console.log(this)

      this.shipping_type = index
    },

    changeUseIntegral: function (e) {
      // this.computedPrice();

      if (this.isIntegral) {
        return
      }

      this.useIntegral = e.mp.detail.value[0]
    },

    // 计算商品价格

    computedPrice() {
      if (this.todayDelivery.supportCity != this.addressInfo.city) {
        // uni.$u.toast('当前地址不支持12小时内送达')
        this.sameDayDelivery = false
      }
      let shipping_type = this.shipping_type
      postOrderComputed(this.orderGroupInfo.orderKey, {
        // addressId: this.addressInfo.id,
        sameDayDelivery: this.sameDayDelivery, // 是否12小时内送达
        cityId: this.addressInfo.cityId,
        addressId: this.addressInfo.id,
        userName: this.addressInfo.consignee,
        userPhone: this.addressInfo.mobile, //电话
        userAddress:
          this.addressInfo.province +
          this.addressInfo.city +
          this.addressInfo.county +
          this.addressInfo.address, //地址

        useIntegral: this.useIntegral ? 1 : 0,

        couponId: this.usableCoupon.id || 0,

        shipping_type: parseInt(shipping_type) + 1,
      }).then(res => {
        const data = res.data

        if (data.status === 'EXTEND_ORDER') {
          this.$yrouter.replace({
            path: '/packageShop/pages/order/OrderDetails/index',

            query: {
              id: data.result.orderId,
            },
          })
        } else {
          this.orderPrice = data.result
        }
      })
    },

    getCartInfo() {
      let cartIds = this.$yroute.query.id
      this.cartid = this.$yroute.query.id
      // 拼团id

      if (this.$yroute.query.pinkId) {
        cartIds = this.$yroute.query.pinkId
      }

      if (!cartIds) {
        uni.showToast({
          title: '参数有误',

          icon: 'none',

          duration: 2000,
        })

        return this.$yrouter.back()
      }

      postOrderConfirm(cartIds)
        .then(res => {
          this.offlinePayStatus = res.data.offline_pay_status

          this.orderGroupInfo = res.data

          this.deduction = res.data.deduction

          this.usableCoupon = res.data.usableCoupon || {}

          // this.addressInfo = res.data.addressInfo || {};

          // 用来显示到店自提的店铺地址

          this.systemStore = res.data.systemStore || {}

          this.storeSelfMention = res.data.storeSelfMention

          this.computedPrice()
        })

        .catch(error => {
          console.log(error)

          uni.showToast({
            title: '加载订单数据失败',

            icon: 'none',

            duration: 2000,
          })
        })
    },

    addressTap: function () {
      this.showAddress = true
      if (!this.addressLoaded) {
        this.addressLoaded = true
        this.$refs.mychild.getAddressList()
      }
    },

    addressRedirect() {
      this.addressLoaded = false

      this.showAddress = false
    },

    couponTap: function () {
      this.showCoupon = true
    },

    changeCoupon: function (coupon) {
      if (!coupon) {
        this.usableCoupon = {
          couponTitle: '不使用优惠券',

          id: 0,
        }
      } else {
        this.usableCoupon = coupon
      }

      this.computedPrice()
    },

    payItem: function (index) {
      this.active = index
    },

    changeAddress(addressInfo) {
      this.addressInfo = addressInfo

      console.log('============地址', this.addressInfo)

      this.computedPrice()
    },

    createOrder() {
      if (!this.addressInfo.id) {
        //
        uni.showToast({
          title: '请选择地址',
          icon: 'none',
          duration: 2000,
        })
        return
      }
      if (this.isIntegral) {
        // 积分支付

        if (this.userInfo.integral < this.orderPrice.payIntegral) {
          uni.showToast({
            title: '积分不足',

            icon: 'none',

            duration: 2000,
          })

          return
        }

        this.active = 'integral'
      }

      let shipping_type = this.shipping_type

      if (!this.isIntegral && !this.active) {
        uni.showToast({
          title: '请选择支付方式',

          icon: 'none',

          duration: 2000,
        })

        return
      }

      if (!this.addressInfo.id && !this.shipping_type) {
        uni.showToast({
          title: '请选择收货地址',

          icon: 'none',

          duration: 2000,
        })

        return
      }

      if (this.shipping_type) {
        if (
          (this.contacts === '' || this.contactsTel === '') &&
          this.shipping_type
        ) {
          uni.showToast({
            title: '请填写联系人或联系人电话',

            icon: 'none',

            duration: 2000,
          })

          return
        }

        if (!/^1(3|4|5|7|8|9|6)\d{9}$/.test(this.contactsTel)) {
          uni.showToast({
            title: '请填写正确的手机号',

            icon: 'none',

            duration: 2000,
          })

          return
        }

        if (!/^[\u4e00-\u9fa5\w]{2,16}$/.test(this.contacts)) {
          uni.showToast({
            title: '请填写您的真实姓名',

            icon: 'none',

            duration: 2000,
          })

          return
        }
      }

      uni.showLoading({
        title: '生成订单中',
      })

      let from = {}

      if (this.$deviceType == 'app') {
        from.from = 'app'
      }

      console.log(this.$deviceType)

      // #ifdef MP-WEIXIN

      subscribeMessage()

      // #endif

      createOrder(this.orderGroupInfo.orderKey, {
        realName: this.contacts,
        sameDayDelivery: this.sameDayDelivery, // 是否开启12小时内送达
        phone: this.contactsTel,
        cityId: this.addressInfo.cityId,
        // addressId: this.addressInfo.id,
        userName: this.addressInfo.realName,
        userPhone: this.addressInfo.phone, //电话
        userAddress:
          this.addressInfo.province +
          this.addressInfo.city +
          this.addressInfo.district +
          this.addressInfo.detail, //地址

        useIntegral: this.useIntegral ? 1 : 0,

        couponId: this.usableCoupon.id || 0,

        payType: this.active,

        pinkId: this.pinkId,

        seckillId: this.orderGroupInfo.seckill_id,

        combinationId: this.orderGroupInfo.combination_id,

        bargainId: this.orderGroupInfo.bargain_id,

        from: this.from,

        mark: this.mark || '',

        shippingType: parseInt(shipping_type) + 1,

        storeId: this.storeItems ? this.storeItems.id : this.systemStore.id,

        ...from,
      })
        .then(res => {
          uni.hideLoading()

          handleOrderPayResults.call(this, res.data, 'create', this.active)
        })

        .catch(err => {
          // handleErrorMessage(err, '创建订单失败')
        })
    },
  },
}
</script>

<style scoped lang="less">
.address {
  width: 702rpx !important;
  border-radius: 20rpx;
  padding: 24rpx !important;
  margin-top: 16rpx !important;
  margin-bottom: 16rpx !important;

  .address-1 {
    margin-right: 15rpx;
  }
}

.footer {
  padding-top: 20rpx !important;
  height: 140rpx !important;
  justify-content: flex-end !important;
  padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx) !important;
}

::v-deep .orderGoods {
  margin-left: 24rpx !important;
  margin-right: 24rpx !important;
  border-radius: 20rpx !important;

  .text {
    width: auto !important;
  }
}
</style>
